<template>
  <div>
    <div @click="toImage()" class="uploadechart">下载</div>
    <van-popup :close-on-click-overlay="false" round v-model="showIMg" position="center">
      <div class="imgDom">
        <van-icon name="close" class="closeBtn" @click="showIMg=false" />
        <p class="tips">长按图片下载</p>
        <img :src="htmlUrl" alt />
      </div>
    </van-popup>
  </div>
</template>

<script type="text/ecmascript-6">
import html2canvas from "html2canvas";
export default {
  name: "Dom2Img",
  props: ["imageTofile"],
  data() {
    return {
      htmlUrl: "",
      showIMg: false
    };
  },
  methods: {
    toImage() {
      this.$toast.loading({
        message: "加载中...",
        loadingType: "spinner",
        overlay: true
      });
      this.show().then(res => {
        // 第一个参数是需要生成截图的元素,第二个是自己需要配置的参数,宽高等
        html2canvas(document.getElementById(this.imageTofile), {
          backgroundColor: null // null 表示设置背景为透明色
        }).then(canvas => {
          let url = canvas.toDataURL("image/png");
          this.htmlUrl = url;
          this.showIMg = true;
          console.log(url);
          // this.saveFile(this.htmlUrl, "img");
        });
      });
    },
    show() {
      return new Promise((reject, resove) => {
        this.$emit("setsy", true);
        reject({ a: 11 });
      });
    }
    // //保存图片
    // saveFile(data, filename) {
    //   var save_link = document.createElementNS(
    //     "http://www.w3.org/1999/xhtml",
    //     "a"
    //   );
    //   save_link.href = data;
    //   save_link.download = filename;
    //   var event = document.createEvent("MouseEvents");
    //   event.initMouseEvent(
    //     "click",
    //     true,
    //     false,
    //     window,
    //     0,
    //     0,
    //     0,
    //     0,
    //     0,
    //     false,
    //     false,
    //     false,
    //     false,
    //     0,
    //     null
    //   );
    //   save_link.dispatchEvent(event);
    //   this.$emit("setsy", false);
    // }
  }
};
</script>
<style scoped lang="less">
.uploadechart {
  position: absolute;
  z-index: 11;
  right: 0.3rem;
  top: 0.68rem;
  background: #e49829;
  color: #ffffff;
  padding: 0.05rem 0.1rem;
  border-radius: 0.06rem;
  font-size: 0.24rem;
}
.imgDom {
  width: 7rem;
  text-align: center;
  padding: 20px;
  overflow: hidden;
  position: relative;
}
.tips {
  font-size: 0.3rem;
  line-height: 0.6rem;
  color: #e49829;
}
.closeBtn {
  font-size: 20px;
  position: absolute;
  right: 0.3rem;
  top: 0.3rem;
}
</style>
 
